import {config, sandBox} from '../../../lib/myapp.js'
import Animation from '../../../utils/animation.js'
Page({
    data: {
        afterSale: {},
        type: 'change',
        retreat: {
            count: 1,
            money: 0,

        },
        img: [],
        textArea: '',

        change: {
            count: 1,
            disparity: 0
        },
        list: [],
        groupList: [],
        allCheck: true,
        channel: 'normal',
        loading: false,
        is_login: true,
        show_select: true,
        specs: [],
        canBuy: true,
        store_count: 0,
        price: 0,
        select_product: null,
        select_count: 0,
        skuTable: {},
        specId: null,
        commodity: {},
        meta: {},
        goodsIndex: 0,
        all: {
            count: 0
        },
        query: {
            spec: {}
        },
        text: '',
        show_search: false,
        searches: [],
        storeList: [],
        show: false,
        isAdd: false,
        reason: [],
        currentReason: ''
    },
    onLoad(e){
        wx.showLoading()
        this.getReason()
        var afterSale = wx.getStorageSync('afterSale')
        afterSale = Object.assign({}, afterSale, {
            color: afterSale.item_meta.specs_text.split(' ')[0],
            size: afterSale.item_meta.specs_text.split(' ')[1]
        })
        if (afterSale) {
            var total = 0
            var list = this.data.list
            if (list.length) {
                list.forEach(v => {
                    total += v.total
                })
            }
            var disparity = total - parseInt(afterSale.unit_price / 100)

            this.setData({
                afterSale: afterSale,
                [`retreat.money`]: afterSale.unit_price / 100,
                [`change.disparity`]: disparity,
            })
        }

    },
    onShow(){
        var oauth = wx.getStorageSync('user_token')
        var locals = wx.getStorageSync('cart_change')

        this.setData({
            list: locals || [],
            is_login: oauth || false
        })
    },
    getReason(){
        sandBox.get({
            api: 'api/system/settings',
            data: {
                type: 'order_refund_reason'
            }
        }).then(v => {
            if (v.statusCode == 200) {
                if (v.data.status && v.data.code == 200) {

                    v.data.data.forEach(item => {
                        item = Object.assign({}, item, {
                            checked: false
                        })
                    })
                    this.setData({
                        reason: v.data.data
                    })
                } else {
                    wx.showModal({
                        content: v.data.message || '请求失败',
                        showCancel: false
                    })
                }
            } else {
                wx.showModal({
                    content: v.data.message || '请求失败',
                    showCancel: false
                })
            }

            wx.hideLoading()
        }).catch(() => {
            wx.showModal({
                content: '服务端错误',
                showCancel: false
            })
            wx.hideLoading()
        })
    },
    showSearch(){
        this.setData({
            show_search: true,
            show_select: true
        })

        var animation = new Animation('showSearch');
        animation.Pullleft()


    },
    changeReason(e){
        var val = e.detail.value

        var reason = this.data.reason
        reason.forEach(v => {
            v.checked = false
            if (v.key == val) {
                v.checked = true
            }
        })

        this.setData({
            currentReason: val
        })
    },
    changeText(e){
        var val = e.detail.value;
        if (val.length > 200) {
            wx.showToast({
                title: '字数不能超过200'
            })

            val = this.data.textArea
        }

        this.setData({
            textArea: val
        })


    },
    changeServiceType(e){
        var value = e.detail.value;
        this.setData({
            type: value
        })
    },
    changeAfterSaleCount(e){
        var type = e.currentTarget.dataset.type;

        var val = parseInt(e.detail.value);
        if (!val) {
            val = 1;
        } else if (!/^[1-9]\d*$/.test(val)) {
            val = val.replace(/[^\d].*$/, '');
            val = parseInt(val) || 1;
        }

        if (val < 0) {
            val = 1;
        } else if (val > this.data.afterSale.quantity) {
            wx.showToast({
                title: '超过最大库存'
            })
            val = parseInt(this.data.afterSale.quantity);
        }

        if (type === 'retreat') {
            this.setData({
                [`${type}.count`]: val,
                [`${type}.money`]: this.data.afterSale.unit_price / 100 * parseInt(val),

            })
        } else {
            var list = this.data.list
            var total = 0
            if (list.length) {
                list.forEach(v => {
                    total += parseInt(v.total)
                })
            }


            var disparity = total - parseInt(this.data.afterSale.unit_price / 100) * val
            this.setData({
                [`${type}.count`]: val,
                [`${type}.disparity`]: disparity
            })
        }


    },
    groupList() {
        if (this.data.list) {
            var data = [];
            var groups = {};

            this.data.list.forEach((v, i) => {
                let channel = v.channel || 'normal';
                if (groups[channel] !== undefined) {
                    data[groups[channel]].items.push(v);
                    data[groups[channel]].index.push(i);
                } else {
                    groups[channel] = data.length;
                    data.push({
                        channel,
                        items: [v],
                        checked: [],
                        index: [i],
                    });
                }
            });
        }

        this.setData({
            groupList: data
        })
    },
    upload() {
        var token = wx.getStorageSync('user_token');
        var count = this.data.img.length - 3;

        if (count != 0) {
            wx.chooseImage({
                count: Math.abs(count),
                success: res => {
                    wx.uploadFile({
                        header: {
                            'content-type': 'multipart/form-data',
                            Authorization: token
                        },
                        url: config.GLOBAL.baseUrl + 'api/O2O/upload',

                        filePath: res.tempFilePaths[0],
                        name: 'avatar_file',
                        success: ret => {
                            if (ret.statusCode == 200) {
                                ret = JSON.parse(ret.data);
                                if (ret.status) {
                                    var img = this.data.img;
                                    img.push(ret.data.url);

                                    this.setData({
                                        img: img
                                    })


                                } else {
                                    wx.showModal({
                                        title: '',
                                        content: ret.message,
                                        showCancel: false
                                    })
                                }
                            } else {
                                wx.showModal({
                                    title: '',
                                    content: '接口错误',
                                    showCancel: false
                                })
                            }
                        }
                    })
                }
            })
        } else {
            wx.showToast({
                title: '不能超过三张'
            })
        }

    },
    removeSearchHistory(e) {
        var searches = JSON.parse(JSON.stringify(this.data.searches));

        searches.splice(e.currentTarget.dataset.index, 1);

        wx.setStorageSync('goods_search_history', searches);

        this.setData({
            searches: searches
        })
    },
    searchHistory(e) {

        var searches = JSON.parse(JSON.stringify(this.data.searches));
        var keyword = searches[e.currentTarget.dataset.index];

        searches.splice(e.currentTarget.dataset.index, 1);
        searches.unshift(keyword);


        wx.setStorageSync('goods_search_history', searches);

        wx.setNavigationBarTitle({
            title: '搜索：' + "'" + keyword + "'"
        })
        this.querySearchList({keyword: keyword});

        this.setData({
            show: false,
            searches: searches,
            text: keyword
        });
    },
    searchKeywords() {

        var keyword = this.data.text;
        if (!keyword || !keyword.length) return;
        var searches = JSON.parse(JSON.stringify(this.data.searches));
        for (let i = 0, len = searches.length; i < len; i++) {
            let search = searches[i];
            if (search === keyword) {
                searches.splice(i, 1);
                break;
            }
        }

        searches.unshift(keyword);
        wx.setStorageSync('goods_search_history', searches);

        wx.setNavigationBarTitle({
            title: '搜索：' + "'" + keyword + "'"
        })
        this.querySearchList({keyword: keyword});

        this.setData({
            show: false,
            searches: searches
        })

    },
    searchKeywords() {

        var keyword = this.data.text;
        if (!keyword || !keyword.length) return;
        var searches = JSON.parse(JSON.stringify(this.data.searches));
        for (let i = 0, len = searches.length; i < len; i++) {
            let search = searches[i];
            if (search === keyword) {
                searches.splice(i, 1);
                break;
            }
        }

        searches.unshift(keyword);
        wx.setStorageSync('goods_search_history', searches);

        wx.setNavigationBarTitle({
            title: '搜索：' + "'" + keyword + "'"
        })
        this.querySearchList({keyword: keyword});

        this.setData({
            show: false,
            searches: searches
        })

    },
    querySearchList(query = {}, page = 1) {
        var params = Object.assign({}, query, {page});

        wx.showLoading({
            title: '加载中',
            mask: true
        });

        sandBox.get({
            api: 'api/store/list',
            data: params,
        }).then(res => {
            res = res.data;

            if (res.status) {
                // var keyReg = new RegExp('(' + this.data.text + ')(?!</i>)', 'g')
                // list.forEach(item => {
                // 	item.name = item.name.replace(keyReg, '<i>$1</i>');
                // })
                this.setData({
                    [`storeList.${page - 1}`]: res.data,
                    meta: res.meta
                })

            } else {
                wx.showModal({
                    title: '',
                    content: res.message
                })
            }
            wx.hideLoading();
        }).catch(rej => {
            wx.showModal({
                title: '',
                content: '请求失败，请稍后重试'
            })
            wx.hideLoading();
        })
    },
    clearSearchHistory() {
        wx.removeStorageSync('goods_search_history');
        this.setData({
            show: false,
            searches: []
        })
    },
    search(e){
        this.setData({
            text: e.detail.value,
        })
    },
    hideSearch(){

        var animation = new Animation('showSearch');
        animation.right().then(() => {
            this.setData({
                show_search: false,
                storeList: []
            })
        })
    },
    disallow_cart() {
        if (!this.data.specs.length) {
            return !this.data.store_count;
        }

        var ids = [], select_product = {}, specs = this.data.specs;
        for (let spec of specs) {
            if (!spec.select) {
                this.setData({
                    price: this.data.commodity.sell_price,
                    select_product: null
                })
                return true;
            }

            ids.push(spec.select);
            for (let v of spec.values) {
                if (v.id === spec.select) {
                    switch (spec.id) {
                        case 2:
                            select_product.img = v.img;
                            select_product.color = v.alias || v.value;
                            select_product.bac = v.color
                            break;
                        default:
                            select_product.size = v.value;
                            select_product.bac = v.color
                    }

                    break;
                }
            }
        }

        if (this.data.skuTable) {
            ids = ids.sort((a, b) => a > b).join('-');
            select_product = Object.assign(select_product, this.data.skuTable[ids]);
        }

        this.setData({
            price: select_product.price,
            select_product: select_product
        })

        return false;
    },
    queryShoppingCount(){
        // var oauth = this.data.is_login
        var oauth = wx.getStorageSync('user_token');

        sandBox.get({
            api: `api/shopping/cart/count`,
            header: {Authorization: oauth},
        }).then(res => {

        }).catch(rej => {

        })
    },
    addStoreNum() {

        // 判断是否登录
        var oauth = wx.getStorageSync('user_token');
        // var cache_store_num = Cache.get(cache_keys.cart);
        var cache_store_num = wx.getStorageSync('cart')
        if (oauth) {
            this.queryShoppingCount();
        } else {
            if (cache_store_num && cache_store_num.length) {
                var store_num = this.data.store_num;
                cache_store_num.forEach(v => {

                    store_num += v.qty;
                })

                this.setData({
                    store_num: store_num
                })
            }
        }
    },
    getGoodsDetail (obj) {
        var that = this;
        return new Promise((resolve, reject) => {
            sandBox.get(obj)
                .then(res => {
                    res = res.data;
                    that.setData({
                        commodity: res.data,
                        meta: res.meta
                    })
                    resolve()
                })
                .catch(err => {
                    console.log(err);
                    reject()
                })
        })

    },
    selectSpec(e){

        var spec = {
            key: e.currentTarget.dataset.key,
            index: e.currentTarget.dataset.index,
            disabled: Number(e.currentTarget.dataset.disabled),
            active: Number(e.currentTarget.dataset.active),
            id: Number(e.currentTarget.dataset.id)
        };

        if (spec.disabled) return;
        var specs = this.data.specs;
        if (!spec.active) {
            for (let item of specs[spec.index].values) {
                if (item.active) {
                    item.active = false;
                    break;
                }
            }
        }

        specs[spec.index].values[spec.key].active = !specs[spec.index].values[spec.key].active
        spec.active = !spec.active;
        specs[spec.index].select = spec.active ? spec.id : '';


        this.setData({
            specs: specs
        })
        var canBuy = this.disallow_cart()
        this.setData({
            canBuy: canBuy
        })
        // this.queryCommodityStore(id, spec.index);
        this.specStore(this.data.result, spec.index)
    },
    specStore(result, key) {

        var data = result.data;
        var specs = this.data.specs;

        if (key === undefined) {

            specs.forEach(spec => {

                for (let v of spec.values) {
                    v.disabled = !data[v.id] || data[v.id].count == 0;
                }
            });


            this.setData({
                specs: specs,
                skuTable: result.table
            })

            var canBuy = this.disallow_cart()


            this.setData({
                canBuy: canBuy
            })

            console.log(specs)
            var count = 0;
            specs.forEach(spec => {
                count++

                if (this.data.specId && !spec.select) {

                    let ids = []
                    var skuTable = this.data.skuTable;
                    Object.keys(skuTable).forEach((v) => {
                        if (skuTable[v].id == this.data.specId) {
                            ids = count ? skuTable[v].ids.reverse() : skuTable[v].ids
                        }
                    })

                    console.log(ids)

                    for (let v of spec.values) {
                        var id = ids[v.index];
                        if (v.id == id && !v.disabled && data[v.id] && data[v.id].count) {
                            v.active = true;
                            spec.select = v.id;
                            this.setData({
                                specs: specs
                            })

                            specs = this.data.specs

                            var canBuy = this.disallow_cart()


                            this.setData({
                                canBuy: canBuy,
                            })


                            this.specStore(result, v.index)

                            return;
                        }


                    }
                }

                if (!spec.select) {
                    for (let v of spec.values) {

                        if (!v.disabled && data[v.id] && data[v.id].count) {
                            v.active = true;
                            spec.select = v.id;
                            this.setData({
                                specs: specs
                            })
                            specs = this.data.specs
                            var canBuy = this.disallow_cart()


                            this.setData({
                                canBuy: canBuy
                            })

                            // this.$emit('specStore', result, v.index);
                            this.specStore(result, v.index)

                            return;
                        }
                    }
                    return
                }

                this.setData({
                    specs: specs
                })

            });


            return;
        }

        var spec = specs[key];
        if (spec.select) {
            this.setData({
                store_count: data[spec.select].count
            })

            for (let i = 0; i < specs.length; i++) {

                if (i === key) continue;
                specs[i].values.forEach(v => {

                    v.disabled = !data[spec.select].specs[v.id].count;

                });


                if (specs[i].select) {
                    this.setData({
                        store_count: data[spec.select].specs[specs[i].select].count,
                    })
                }

                this.setData({
                    specs: specs
                })
            }
        } else {

            this.setData({
                store_count: this.data.commodity.store
            })


            for (let i = 0; i < specs.length; i++) {

                if (i === key) continue;

                specs[i].values.forEach(v => {
                    v.disabled = !data[v.id] || !data[v.id].count;
                });


                if (specs[i].select) {
                    this.setData({
                        store_count: data[specs[i].select].count,
                    })

                }

                this.setData({
                    specs: specs
                })


            }

        }

        if (parseInt(this.data.select_count) > this.data.store_count) {
            this.setData({
                select_count: String(this.data.store_count)
            })

        } else if (parseInt(this.data.select_count) === 0) {
            this.setData({
                select_count: '1'
            })
        }
        this.setData({
            specs: specs,
        })


        var canBuy = this.disallow_cart()


        this.setData({
            canBuy: canBuy
        })
    },
    calcAfterSaleCount(e){
        var type = e.currentTarget.dataset.type
        var count = type == 'retreat' ? parseInt(this.data.retreat.count) : parseInt(this.data.change.count)
        var index = e.currentTarget.dataset.index
        var val = count + (parseInt(index) ? 1 : -1)

        if (val > 0 && val <= parseInt(this.data.afterSale.quantity)) {


            if (type === 'retreat') {
                this.setData({
                    [`${type}.count`]: val,
                    [`${type}.money`]: this.data.afterSale.unit_price / 100 * parseInt(val),

                })
            } else {
                var list = this.data.list
                var total = 0
                if (list.length) {
                    list.forEach(v => {
                        total += parseInt(v.total)
                    })
                }


                var disparity = total - parseInt(this.data.afterSale.unit_price / 100) * val

                this.setData({
                    [`${type}.count`]: val,
                    [`${type}.disparity`]: disparity
                })
            }
        } else {
            wx.showToast({
                title: '超出最大库存',
                image: '../../../assets/image/error.png'
            })
        }

    },
    changeCount(e){

        var select_count = parseInt(this.data.select_count)

        var index = e.target.dataset.index
        var val = select_count + (parseInt(index) ? 1 : -1)

        if (val > 0 && val <= parseInt(this.data.store_count)) {
            this.setData({
                select_count: val
            })


        } else {
            wx.showToast({
                title: '超出最大库存',
                image: '../../../assets/image/error.png'
            })
        }
    },
    submit(){
        var type = this.data.type
        if (!this.data.currentReason) {
            wx.showModal({
                content: '请选择申请理由',
                showCancel: false
            })

            return;
        }




        var oauth = wx.getStorageSync('user_token')

        if (type === 'retreat') {

            var data = {
                order_id: this.data.afterSale.order_id,
                order_item_id: this.data.afterSale.id,
                quantity: this.data.retreat.count,
                images: this.data.img,
                type: 1,
                content: this.data.textArea || '无',
                reason: this.data.currentReason,
                amount: this.data.retreat.money
            }

            sandBox.post({
                api: 'api/O2O/refund/applyReturn',
                data: data,
                header: {Authorization: oauth},
            }).then(res => {
                res = res.data;
                if (res.data && res.code == 200) {
                    var refund_no = res.data.refund.refund_no
                    wx.redirectTo({
                        url:`/pages/afterSales/complete/complete?refund_no=${refund_no}`
                    })
                } else {
                    wx.showModal({
                        content:res.message || '获取接口数据失败',
                        showCancel:false
                    })
                }
            }).catch(() => {
                wx.showModal({
                    content:'服务端出错',
                    showCancel:false
                })
            })
        } else {
            if (!this.data.list.length) {
                wx.showModal({
                    content: '请添加需要换货的商品',
                    showCancel: false
                })

                return;
            }

            var list = this.data.list;


            var data = {
                order_id: this.data.afterSale.order_id,
                order_item_id: this.data.afterSale.id,
                quantity: this.data.change.count,
                images: this.data.img,
                type: 2,
                content: this.data.textArea || '无',
                reason: this.data.currentReason,
                amount: this.data.change.disparity,
                exchangeData: list.map(v => {
                    return {
                        name: v.name,
                        qty: v.qty,
                        price: parseInt(v.price),
                        product_id: v.product_id,
                        goods_id: v.goods_id,
                        image: v.image
                    }
                })
            }

            sandBox.post({
                api: '/api/O2O/refund/applyExchange',
                data: data,
                header: {Authorization: oauth},
            }).then(res => {
                res = res.data
                if (res.code == 200 && res.data.refund){

                    if (res.data.need_pay) {
                        //补差价 TODO
                        var order_no = res.data.order.order_no
                        wx.setStorageSync('refund_no',res.data.refund.refund_no)
                        wx.redirectTo({
                            url:`/pages/store/payment/payment?order_no=${order_no}&isDisparity=true`
                        })
                    }
                  // var refund_no = res.data.refund.refund_no
                  //   wx.redirectTo({
                  //       url:`/pages/afterSales/complete/complete?refund_no=${refund_no}`
                  //   })
                } else {
                    wx.showModal({
                        content:res.message || '获取接口数据失败',
                        showCancel:false
                    })
                }
            }).catch(() => {
                wx.showModal({
                    content:'服务端出错',
                    showCancel:false
                })
            })
        }
    },
    removeFromCart(e){
        // var oauth = this.data.is_login;
        var index = e.target.dataset.index;
        var list = this.data.list;
        var total = 0
        if (list.length && list.length >= index + 1) {
            list.splice(index, 1)
            list.forEach(v => {
                total += v.total
            })
            var disparity = total - parseInt(this.data.afterSale.unit_price / 100) * this.data.change.count
            this.setData({
                list: list,
                [`change.disparity`]: disparity
            })
            this.removed(true, index)
        }

        else {
            this.removed(false)
        }


    },
    showSelect(e){
        this.setData({
            show_select: false
        })


        var animation = new Animation('show');
        animation.positionInit()

        new Animation('black').show()
    },
    addSearchGoods(){

        var item = this.data.select_product
        if (item) {
            var data = {
                product_id: item.id,
                goods_id: this.data.commodity.id,
                image: item.img,
                name: this.data.commodity.name,
                price: item.price,
                qty: this.data.select_count,
                size: item.size,
                color: item.color,
                sku: item.sku,
                total: parseInt(item.price) * parseInt(this.data.select_count),
                edit: false

            }
            var total = 0
            var list = this.data.list
            list.push(data)
            list.forEach(v => {
                total += v.total
            })
            this.setData({
                list: list
            })

            var disparity = total - parseInt(this.data.afterSale.unit_price / 100) * this.data.change.count
            this.setData({
                list: list,
                [`change.disparity`]: disparity
            })
        }

        this.hideSearch()
        this.closeSelect();
    },
    addCart(success, message) {
        // this.$refs.button.finish();
        this.setData({
            loading: false,

        })
        if (success) {

            wx.removeStorageSync('cart')

            // TODO
            //this.$emit('readyCheckout');
            if (this.data.isAdd) {
                this.setData({
                    isAdd: false,
                    text: ''
                })

                this.hideSearch()
            }
            // this.queryCartList();


            this.closeSelect()

        } else {

            wx.showModal({
                title: message || '保存本地购物车失败,请重试！'

            })
            this.closeSelect()
            this.select_products()
            this.groupList()
        }


    },
    appendToCart(data) {
        var oauth = wx.getStorageSync('user_token');
        if (!oauth) return;

        if (!Array.isArray(data)) {
            data = [data];
        }

        console.log(data)

        var json = {};
        data.forEach((v, i) => json[i] = v);
        data = json;

        sandBox.post({
            api: `api/shopping/cart`,
            data: data,
            header: {Authorization: oauth},

        }).then(res => {
            res = res.data;
            if (res.status) {
                this.addCart(true)
            } else {
                this.addCart(false, res.message)
            }
        }).catch(rej => {
            this.addCart(false)
        })
    },
    closeSelect(){
        var list = this.data.list;
        list.forEach((v) => {
            v.edit = false
        })

        var animation = new Animation('show');
        new Animation('black').hide()
        animation.up().then(() => {
            this.setData({
                show_select: true,
                list: list
            })
        })


    },
    editGoods(e){

        const [id, index, size, qty, list, specId] = [e.target.dataset.id, e.target.dataset.index, e.target.dataset.size, e.target.dataset.qty, this.data.list, e.target.dataset.specid]


        list.forEach((v, i) => {
            i == index ? v.edit = true : v.edit = false
        })
        this.setData({
            list: list,
            goodsIndex: index,
            specId: specId,
            isAdd: false
        })
        this.showSelect()
        this.getGoodsDetail({
            api: `api/store/detail/${id}`,
            data: {include: 'photos,products,oneComment,guessYouLike,whoLike,point'}
        }).then(() => {
            this.queryCommodityStore(id)
        })
    },
    confirm(){
        var list = this.data.list;
        var total = 0
        list.forEach(v => {
            if (v.goods_id === this.data.commodity.id) {

                var select_product = this.data.select_product;
                v = Object.assign(v, {
                    color: select_product.color,
                    size: select_product.size,
                    qty: this.data.select_count,
                    total: parseInt(select_product.price) * this.data.select_count
                })

                total += v.total


            }


            var disparity = total - parseInt(this.data.afterSale.unit_price / 100) * this.data.change.count
            this.setData({
                list: list,
                [`change.disparity`]: disparity
            })

            this.closeSelect()
        })


    },
    removed (success, index){
        if (success) {

            // this.queryCartList()
            // var list = this.data.list
            // var product = list.splice(index, 1)[0];


            this.closeSelect()
            this.select_products()
            this.groupList();


        } else {
            wx.showToast({
                title: '删除购物车商品失败！',
                image: '../../../assets/image/error.png'
            })
        }
    },
    select_products() {
        var data = {
            count: 0,
            total: 0,
            __ids: []
        }

        this.data.list.forEach((v) => {
            if (v.checked) {
                data.count += parseInt(v.qty);
                data.total += Number(v.total);
                data.__ids.push(v.__raw_id || v.index);
            } else {
                this.setData({
                    allCheck: false
                })
            }
        })

        this.setData({
            all: data
        })
    },
    modifyCount(e){

        var val = parseInt(e.detail.value);
        if (!val) {
            val = 1;
        } else if (!/^[1-9]\d*$/.test(val)) {
            val = val.replace(/[^\d].*$/, '');
            val = parseInt(val) || 1;
        }

        if (val < 0) {
            val = 1;
        } else if (val > this.data.store_count) {
            wx.showToast({
                title: '超过最大库存'
            })
            val = parseInt(this.data.store_count);
        }

        this.setData({
            select_count: val
        })

    },
    showSpec(e){
        var id = e.currentTarget.dataset.id
        this.setData({
            isAdd: true
        })
        this.getGoodsDetail({
            api: `api/store/detail/${id}`,
            data: {include: 'photos,products,oneComment,guessYouLike,whoLike,point'}
        }).then(() => {
            this.queryCommodityStore(id)
            this.showSelect()
        })
    },

    queryCommodityStore(id, key){
        var that = this;
        var oauth = wx.getStorageSync('user_token')
        sandBox.get({api: `api/O2O/store/${id}/edit`, header: {Authorization: oauth},})
            .then(res => {

                res = res.data
                if (!res.status || !res.data || !res.data.specs) return;
                if (res.data.specs && typeof key === 'undefined') {
                    let specs = [];

                    Object.keys(res.data.specs)
                        .forEach((key, index) => {
                            let value = res.data.specs[key];
                            value.select = '';
                            value.values = value.list
                                .map(v => {
                                    return Object.assign({
                                        index: index,
                                        active: false,
                                        disabled: false
                                    }, v);
                                });

                            delete value.list;
                            specs.push(value);
                        });

                    that.setData({
                        specs: specs
                    })

                    console.log(specs)

                    var canBuy = this.disallow_cart()


                    this.setData({
                        canBuy: canBuy
                    })
                }


                if (res.data.stores) {
                    let data = {};
                    Object.keys(res.data.stores)
                        .forEach(key => {
                            let value = res.data.stores[key];

                            value.ids.forEach(id => {
                                data[id] = data[id] || {count: 0, specs: {}};
                                data[id].count += parseInt(value.store);

                                value.ids.forEach(i => {
                                    if (i === id) return;

                                    data[id].specs[i] = {
                                        count: parseInt(value.store)
                                    };
                                })
                            });
                        });
                    // console.log(data);
                    var result = {data, table: res.data.stores};

                    this.setData({
                        result: result
                    })
                    that.specStore(result, key)
                    // this.$emit('specStore', result, key);
                }

            })
            .catch(err => {

            })
    },
})